<template>
  <basic-dialog :visible="show"
                minWidth="1020px"
                :title="title"
                isShowClose
                @submit="submit"
                :isShowInnerLoading="isShowInnerLoading"
                isShowBasicFooter
                @close="hideDialog">
    <div class="padding-20">
      <div class="flex items-center padding-b-20">
        <select-input :list="searchCondition" @search="inputSearch" @clearSearchVal="clearSearchVal"/>
        <div class="form-inline" style="padding: 0;margin-left: 80px">
          <slot />
        </div>
      </div>
      <unfold>
        <!-- 左侧组名称列表 -->
        <template v-slot:tree-list>
          <div>
            <div class="left box tree-list">
              <div  style="height: 336px" class="tree-content bg-white overflow-auto scrollbar">
                <div>
                  <tree-item v-for="(item, index) in treeList" :key="index" :item="item" :activeId="activeId" :ellipsis="false"/>
                </div>
              </div>
            </div>
          </div>
        </template>
        <template v-slot:content>
          <div class="right box page-content " style="display: flex;position: relative;flex-direction: column; height: 338px">
            <!-- 表格 -->
            <q-table
              class="users-table myTable scroll my-sticky-virt scroll-table inherit"
              :columns="tableColumns"
              :data="users"
              row-key="id"
              :pagination.sync="pagination"
              selection="single"
              color="primary"
              :hide-bottom="!!users.length"
              :loading="tableLoading"
              style="margin: 0;max-height: 336px"
            >
              <template v-slot:body="props">
                <q-tr :props="props">
                  <q-td auto-width>
                    <!--                    <q-radio dense v-model="selectedUsers[0].id" :val="props.row.id" />-->
                    <q-checkbox size="xs" v-model="selectedUser" :val="props.row.id"/>
                  </q-td>
                  <q-td>
                    {{ props.row.number}}
                  </q-td>
                  <q-td>
                    {{ props.row.name}}
                  </q-td>
                  <q-td>
                    {{ getRoleNamesByRoles(props.row.roles) }}
                    <q-tooltip v-if="getRoleNamesByRoles(props.row.roles)">{{ getRoleNamesByRoles(props.row.roles) }}</q-tooltip>
                  </q-td>
                  <q-td>{{getPostNameByCode(props.row.postCode)}}</q-td>
                </q-tr>
              </template>
            </q-table>
          </div>
        </template>
      </unfold>
    </div>
  </basic-dialog>
</template>

<script>
import Unfold from 'src/components/unfold'
import TreeItem from 'src/components/tree-list/item'
import userManageApi from 'src/boot/system/user-manage'
import { gethashcode } from 'src/assets/js/util'
import { getDict } from 'src/boot/common/dict'
import SelectInput from 'src/components/select-input/index'

export default {
  name: 'PeopleSelect',
  components: {
    Unfold,
    TreeItem,
    SelectInput
  },
  props: {
    title: {
      type: String,
      default: '人员选择'
    },
    needCheck: { // 是否需要校验
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      show: false,
      isShowInnerLoading: false,
      searchData: '',
      treeList: [],
      // 选中的idHash
      activeId: null,
      thumbStyle: this.CommonConfig.thumbStyle, // 滚动条样式
      // 表格列
      tableColumns: [
        { name: 'number', field: 'number', label: '员工编号', align: 'left' },
        { name: 'name', field: 'name', label: '姓名', align: 'left' },
        { name: 'roles', field: 'roles', label: '角色', align: 'left' },
        { name: 'post', field: 'post', label: '岗位', align: 'left' }
      ],
      // 用户数组
      users: [],
      pagination: {
        rowsPerPage: 0
      },
      // 选中的用户
      selectedUser: [],
      selectedUsers: [{
        id: null
      }],
      list: [],
      queryParams: {
        searchBy: '', // 搜索条件 name 人名
        keyword: '', // 搜索值
        // 部门 ID
        departmentId: null
      },
      postOptions: [],
      tableLoading: false,
      searchCondition: [{ id: 'name', name: '人名' }, { id: 'number', name: '员工编号' }]
    }
  },
  created () {
  },
  destroyed () { // 在组件销毁之前清除自定义事件
    this.CommonConfig.event.$off('change-activeid')
  },
  methods: {
    /**
     * 点击确定
     */
    submit () {
      const selectId = this.selectedUser[0]
      const selectUserInfo = this.users.find((item) => {
        return item.id === selectId
      })
      this.$emit('selectUser', selectUserInfo)
      !this.needCheck && this.hideDialog()
    },
    /**
     * 显示弹框
     */
    showDialog () {
      this.show = true
      this.getDepartmentsTree()
      this.getDictList()
      this.CommonConfig.event.$on('change-activeid', (id, item) => {
        if (this.queryParams.departmentId !== item.id) {
          this.activeId = id
          this.queryParams.departmentId = item.id
          this.listUsers()
        }
      })
    },
    /**
     * 隐藏弹框
     */
    hideDialog () {
      this.CommonConfig.event.$off('change-activeid')
      this.show = false
      this.$emit('close')
    },
    /**
     * 获取部门 tree
     */
    getDepartmentsTree () {
      this.isShowInnerLoading = true
      userManageApi.getDepartmentsTree()
        .then(data => {
          this.list = data
          this.isShowInnerLoading = false
          this.setTree(this.list)
        })
    },
    setTree (list) {
      this.treeList = this.initTree(list)
      // 首次指定部门
      if (!this.activeId) {
        this.treeList.forEach(item => {
          if (!this.activeId) {
            this.activeId = item.idHash
            this.queryParams.departmentId = item.id
          }
        })
      }
      this.listUsers()
    },
    // 给list添加数据
    initTree (info, open = true) {
      return info.map(item => {
        if (item.children && item.children.length > 0) {
          item.children = this.initTree(item.children)
        }
        return {
          ...item,
          open,
          idHash: gethashcode()
        }
      })
    },

    /**
     * 列举用户
     */
    listUsers () {
      this.users = []
      this.tableLoading = true
      this.isShowInnerLoading = true
      userManageApi.listUsersNoPage(this.queryParams)
        .then(data => {
          if (data.length > 0) {
            this.selectedUser[0] = data[0].id
          }
          // if (data.length > 0) {
          //   this.selectedUsers[0].id = data[0].id
          // } else {
          //   this.selectedUsers[0].id = null
          // }

          this.users = data

          // this.pagination.rowsNumber = data.total
        })
        .finally(() => {
          this.isShowInnerLoading = false
          this.tableLoading = false
        })
    },
    /**
     * 根据角色对象数组获取拼接的角色名
     * @param roles 角色对象数组
     * @return {string} 拼接的角色名
     */
    getRoleNamesByRoles (roles) {
      let names = ''
      for (let i in roles) {
        let role = roles[i]
        if (role === undefined) {
          break
        }
        names += ', ' + role.name
      }
      names = names.substr(2)

      return names
    },
    // 获取岗位名
    getPostNameByCode (id) {
      let label = ''
      if (id) {
        this.postOptions.forEach(item => {
          if (item.value === id) {
            label = item.label
          }
        })
      }
      return label
    },
    // 岗位
    getDictList () {
      getDict('post', true).then(data => {
        this.postOptions.push(...data.data)
      })
    },
    // 搜索
    inputSearch (item, searchVal) {
      this.queryParams.searchBy = item.id
      this.queryParams.keyword = searchVal
      this.pagination.page = 1
      this.listUsers()
    },
    // 清空
    clearSearchVal () {
      this.queryParams.searchBy = ''
      this.queryParams.keyword = ''
      this.listUsers()
    }
  },
  watch: {
    show () {
      this.queryParams.searchBy = ''
      this.queryParams.keyword = ''
      this.activeId = null
      this.users = []
      this.selectedUser = []
    },
    selectedUser (val) {
      if (val && val.length > 1) {
        val.shift()
      }
    }
  }
}
</script>

<style scoped lang="stylus">
>>>.toggle-hide{
  display none
}
>>>.tree-bg .tree-line{
  border none
  height: 32px;
  line-height: 32px;
}
>>>.dialog-content .name{
  font-size 16px
}
>>>.right-part{
  padding 0 !important
}
>>>.left-part{
  min-width: 300px!important;
  max-width: 300px!important;
  margin-right: 20px !important;
}
.tree-list {
  display flex
  flex-direction column
  width 300px
  border-radius 6px
  overflow hidden
  height 338px
  border 1px #D3D3D3 solid

  .tree-content {
    flex 1
    min-height calc(100% - 40px)
    /*padding-bottom 20px*/
  }

  .toggle-icon {
    transition transform 300ms ease-in

    &.fold {
      transform rotate(-90deg)
    }
  }
}
</style>
